﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Storage;
using Storage.EntityModels;
using Storage.Exceptions;
using Security;
using System.Resources;

namespace TripLOA.GUI.roles
{
    public partial class RolesToUsers : TripLOA.GUI.internationalization.LOABasePage
    {

        #region PROPERTIES

        /// <summary>
        /// contains the initial letter or pattern in order to display usernames in the grid
        /// </summary>
        private string UsernameToMatch
        {
            get
            {
                object o = ViewState["UsernameToMatch"];
                if (o == null)
                    return string.Empty;
                else
                    return (string)o;
            }
            set
            {
                ViewState["UsernameToMatch"] = value;
            }
        }

        /// <summary>
        /// the index of grid pagination
        /// </summary>
        private int PageIndex
        {
            get
            {
                object o = ViewState["PageIndex"];
                if (o == null)
                    return 0;
                else
                    return (int)o;
            }
            set
            {
                ViewState["PageIndex"] = value;
            }
        }

        /// <summary>
        /// the number of user each grid's page have to show
        /// </summary>
        private int PageSize
        {
            get
            {
                return 10;
            }
        }

        /// <summary>
        /// holds the current repeater event of the grid
        /// </summary>
        private string RepeaterEvent
        {
            get
            {
                object o = ViewState["RepeaterEvent"];
                if (o == null)
                    return "";
                else
                    return (string)o;
            }
            set
            {
                ViewState["RepeaterEvent"] = value;
            }
        }

        #endregion PROPERTIES


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                RepeaterEvent = "";
                // Display those users belonging to the currently selected role 
                DisplayUsersBelongingToAdministrators();

                //Bind Users to ManageUsers GridView
                this.UsernameToMatch = "A"+"%";
                BindUsersToManageUsers();
                BindFilteringUI();

                //Display total users and online users
                DisplayTotalAndOnlineNumber();
            }
        }

        
        #region USERS_GRID
        
      

        /// <summary>
        /// binds users to ManageUsers GridView managing the
        /// command from the Repeater and the UNREGISTERED command.
        /// </summary>
        protected void BindUsersToManageUsers()
        {
            int totalRecords=0;

            if (!RepeaterEvent.Equals("UNREGISTERED"))
            {
                ManageUsers.DataSource = Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords );
                ManageUsers.DataBind();
            }
            else
            {
                MembershipUserCollection muc = Membership.GetAllUsers();
                MembershipUserCollection unreg_c = new MembershipUserCollection();
                
                foreach ( MembershipUser u in muc)
                {
                    try
                    {
                        if (!StorageManager.Instance.GetUserByUserName(u.UserName).BookedIn)
                        {
                            unreg_c.Add(u);
                        }
                    }
                    catch (Storage.Exceptions.UserNotFoundException)
                    {
                        /*
                         * This happens when a user has been created in the membership provider 
                         * but not in the "profile" databases. Users like these are only "users 
                         * for testing phases" and they are not counted as "Unregistered".
                         */
                    }
                 }

                ManageUsers.DataSource = unreg_c;
                ManageUsers.DataBind();

              }

            //Enable or disable the paging interface
            bool visitingFirstPage = (this.PageIndex == 0);
            lnkFirst.Enabled = !visitingFirstPage;
            lnkPrev.Enabled = !visitingFirstPage;

            int lastPageIndex = (totalRecords - 1) / this.PageSize;
            bool visitingLastPage = (this.PageIndex >= lastPageIndex);
            lnkNext.Enabled = !visitingLastPage;
            lnkLast.Enabled = !visitingLastPage;

    
           }
     

        /// <summary>
        /// creates the "per letter" users selection.
        /// </summary>
        protected void BindFilteringUI()
        {
            string[] filterOptions = { "All", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Other", "UNREGISTERED" };
            FilteringUI.DataSource = filterOptions;
            FilteringUI.DataBind();
        }

        /// <summary>
        /// defines the string pattern according to the selected link of the Repeater
        /// </summary>
        protected void FilteringUI_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (!this.UsernameToMatch.Equals(e.CommandName))
                PageIndex = 0;

            if (e.CommandName == "All" || e.CommandName == "UNREGISTERED")
            {                
                RepeaterEvent = "All";
                if (e.CommandName.Equals("UNREGISTERED")) RepeaterEvent = "UNREGISTERED";
                else RepeaterEvent = "All";
                this.UsernameToMatch = string.Empty;                
            }
            else
            {
                if (e.CommandName == "Other")
                {
                    RepeaterEvent="Other";
                    this.UsernameToMatch = "^a-z";
                }

                else
                {
                    RepeaterEvent = e.CommandName;
                    this.UsernameToMatch = e.CommandName;
                }
            }

            BindUsersToManageUsers();
        }

        /// <summary>
        /// displays the total number of users that are not unregistered and the number of online users
        /// </summary>
        private void DisplayTotalAndOnlineNumber()
        {
            label_tot_num.Text = Security.SecuritySQLMembershipProvider.GetTotalUsers().ToString();            
            label_online_num.Text = Membership.GetNumberOfUsersOnline().ToString();
        }

        #endregion USERS_GRID

        
        #region DISPLAY_ADMINISTRATORS

        /// <summary>
        /// manages the deletion of a user from a specific role
        /// </summary>
        protected void RolesUserList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // Get the selected role 
            string selectedRoleName = "Administrators";

            Label UserNameLabel = RolesUserList.Rows[e.RowIndex].FindControl("UserNameLabel") as Label;

            //An admin cannot accidentally delete himself from admin role
            if (selectedRoleName.Equals("Administrators") &&
                UserNameLabel.Text.Equals(Page.User.Identity.Name))
            {
                // Display a status message 
                lab_status.Text = string.Format("An admin cannot delete himself from Administrators role");
            }
            else
            {
                // Remove the user from the role 
                Roles.RemoveUserFromRole(UserNameLabel.Text, selectedRoleName);

                // Refresh the GridView 
                DisplayUsersBelongingToAdministrators();

                // Display a status message 
                lab_status.Text = string.Format("User {0} was removed from role {1}.", UserNameLabel.Text, selectedRoleName);
            }
        }

        /// <summary>
        /// display the users according to the selected role
        /// </summary>
        private void DisplayUsersBelongingToAdministrators()
        {
            // Get the role "Administrators" 
            string selectedRoleName = "Administrators";

            // Get the list of usernames that belong to the role 
            string[] usersBelongingToRole = Roles.GetUsersInRole(selectedRoleName);

            // Bind the list of users to the GridView 
            RolesUserList.DataSource = usersBelongingToRole;
            RolesUserList.DataBind();
        }

        /*
        /// <summary>
        /// displays users (on event "indexchanged") belonging to the selected role
        /// </summary>
        protected void RoleList_SelectedIndexChanged(object sender, EventArgs e)
        {
            DisplayUsersBelongingToRole();
        }
        */

        /*
        /// <summary>
        /// binds roles to the dropdown list that shows roles
        /// </summary>
        private void BindRolesToList()
        {
            // Get all of the roles 
            string[] roles = Roles.GetAllRoles();

            RoleList.DataSource = roles;
            RoleList.DataBind();
        }*/


        #endregion DISPLAY_ADMINISTRATORS


        #region DELETE_USER
        /// <summary>
        /// code behind the button to delete a user
        /// </summary>
        protected void but_deleteuser_Click(object sender, EventArgs e)
        {
            string user_to_be_deleted = txt_deleteuser.Text;

            if (!Page.User.Identity.Name.Equals(user_to_be_deleted))
            {

                if (Membership.DeleteUser(user_to_be_deleted, false))
                {
                    //Remove user from roles in order to prevent currently-logged deleted user to access secured sections

                    Roles.RemoveUserFromRoles(user_to_be_deleted,Roles.GetRolesForUser(user_to_be_deleted));

                    string userdeleted = GetLocalResourceObject("UserDeleted.Text").ToString();
                    lab_status.Text = string.Format(userdeleted+" : {0}.", user_to_be_deleted);
                    BindUsersToManageUsers();
                    DisplayUsersBelongingToAdministrators();
                    DisplayTotalAndOnlineNumber();
                }
                else
                {
                    string usernotpresent = this.GetLocalResourceObject("UserNotPresent.Text").ToString();
                    lab_status.Text = string.Format(usernotpresent +" : {0}.", user_to_be_deleted);
                }
            }
            else
            {
                string adminerror = this.GetLocalResourceObject("AdminError.Text").ToString();
                lab_status.Text = string.Format(adminerror+" : {0}.", user_to_be_deleted);
            }
        }

        #endregion DELETE_USER


        #region MANAGE_PAGINATION


        protected void lnkFirst_Click(object sender, EventArgs e)
        {
            this.PageIndex = 0;
            BindUsersToManageUsers();
        }

        protected void lnkPrev_Click(object sender, EventArgs e)
        {
            this.PageIndex -= 1;
            BindUsersToManageUsers();
        }

        protected void lnkNext_Click(object sender, EventArgs e)
        {
            this.PageIndex += 1;
            BindUsersToManageUsers();
        }

        protected void lnkLast_Click(object sender, EventArgs e)
        {
            // Determine the total number of records
            int totalRecords;
            Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords);
            // Navigate to the last page index
            this.PageIndex = (totalRecords - 1) / this.PageSize;
            BindUsersToManageUsers();
        }
        #endregion MANAGE_PAGINATION
    }
}
